import { compareSync } from 'bcryptjs';
import {
  Injectable,
  HttpException,
  HttpStatus,
  NotFoundException,
} from '@nestjs/common';
import * as bcrypt from 'bcryptjs';
import { InjectRepository } from '@nestjs/typeorm';
import { CreateUserDto, ListUserDTO } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
import { ILike, Repository } from 'typeorm';
import { WechatUserInfo } from '../auth/auth.interface';
import { UserEntity } from './entity/user.entity';
import { getPagination, mapToObj } from 'src/utils';

@Injectable()
export class UserService {
  constructor(
    @InjectRepository(UserEntity)
    private userRepository: Repository<UserEntity>,
  ) {}

  /**
   * 账号密码注册
   * @param createUser
   */
  async register(createUser: CreateUserDto) {
    const { username } = createUser;

    const user = await this.userRepository.findOne({
      where: { username },
    });
    if (user) {
      throw new HttpException('用户名已存在', HttpStatus.BAD_REQUEST);
    }
    const newUser = await this.userRepository.create(createUser);
    return await this.userRepository.save(newUser);
  }

  /**
   * 微信注册
   * @param userInfo
   * @returns
   */
  async registerByWechat(userInfo: WechatUserInfo) {
    // const { nickname, openid, headimgurl } = userInfo;
    const newUser = await this.userRepository.create(userInfo);
    return await this.userRepository.save(newUser);
  }

  // 获取用户列表
  async findAll(query: ListUserDTO): Promise<any> {
    const { page = 1, pageSize = 10, username, email } = query;
    // 自定义查询条件
    const queryMap = new Map();
    queryMap.set('del_flag', 0);
    if (username) {
      queryMap.set('username', ILike(username));
    }
    if (email) {
      queryMap.set('email', ILike(email));
    }
    const getList = this.userRepository
      .createQueryBuilder('sys_user')
      .where(mapToObj(queryMap))
      .select([
        'sys_user.id',
        'sys_user.username',
        'sys_user.nickname',
        'sys_user.avatar',
        'sys_user.email',
        'sys_user.role',
        'sys_user.create_time',
        'sys_user.update_time',
      ])
      .skip((page - 1) * pageSize)
      .take(pageSize)
      .printSql()
      .getManyAndCount();

    const [list, total] = await getList;
    const pagination = getPagination(total, pageSize, page);
    const result = {
      result: list,
      pagination,
    };

    return result;
  }

  // 通过id获取指定角色信息
  async findById(query) {
    const { id } = query;
    const sql = `SELECT id,username,nickname,avatar,role,email,update_time FROM sys_user WHERE id ='${id}' AND del_flag=0`;
    const roleDetial = await this.userRepository.query(sql);
    if (roleDetial.length == 0) {
      throw new NotFoundException('找不到对应id数据');
    }
    const result = {
      result: roleDetial[0],
    };
    return result;
  }

  // 更新用户
  async update(id: string, body: UpdateUserDto) {
    let password_hash = '';
    const { password } = body;
    if (password.length < 10) {
      password_hash = bcrypt.hashSync(password, 10);
    }
    body.password = password_hash;
    const reslut = await this.userRepository.update(id, body);
    return reslut;
  }

  // 删除用户
  async remove(query) {
    const { id } = query;
    const sql = `SELECT username,id FROM sys_user WHERE id ='${id}' AND del_flag=0`;
    const existRole = await this.userRepository.query(sql);
    if (existRole.length == 0) {
      throw new HttpException(`id为${id}的用户不存在`, 401);
    }
    const update_sql = `UPDATE sys_user SET del_flag=1 WHERE id='${id}'`;
    const result = await this.userRepository.query(update_sql);
    if (result) {
      return '删除成功！';
    } else {
      return '删除失败！';
    }
  }

  // 密码盐
  comparePassword(password, libPassword) {
    return compareSync(password, libPassword);
  }

  async findByOpenid(openid) {
    return await this.userRepository.findOne(openid);
  }
}
